package com.xiaoyi.tool.http;

import android.content.Context;

import com.xiaoyi.tool.http.tools.NetUtil;
import com.xiaoyi.tool.http.tools.OkHttpLogTool;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class HttpClient {
    private static String token = "";
    private static Retrofit retrofit;
    private static HashMap<String, HttpClient> clients = new HashMap<>();

    private HttpClient(String baseUrl ,Context context) {
        retrofit = new Retrofit.Builder()
                // 设置接口主地址
                .baseUrl(baseUrl)
                // 配置 HTTP 请求客户端
                .client(getHttpRequestClient(context))
                // 配置json 转换器
                .addConverterFactory(GsonConverterFactory.create())
                // 添加支持 - 返回值定义为Observable对象
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
    }


    public   <T> T createApi(Class<T> clazz) {
        // 获取接口实例
        return retrofit.create(clazz);
    }

    public static HttpClient getInstance(String baseUrl ,Context context){
        if(!clients.containsKey(baseUrl))
        {
            HttpClient httpClient = new HttpClient(baseUrl ,context);
            clients.put(baseUrl, httpClient);
        }
        // 一个主地址 对应一个client
        return clients.get(baseUrl);
    }


    /**
     *  定制 http 访问访问器
     */
    private OkHttpClient getHttpRequestClient(final Context context) {
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor( new OkHttpLogTool());
        // 打印获取到的信息。 （不设置不打印）
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        //设置缓存路径
        String cacheDir = context.getExternalCacheDir().getAbsolutePath() ;
        File httpCacheDirectory = new File(cacheDir , "OKHttpResponses");
        //设置缓存 大小
        Cache cache = new Cache(httpCacheDirectory, 50 * 1024 * 1024);
        // 自定义拦截器
        Interceptor interceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request()
                        .newBuilder()
                        .addHeader("token", token)
                        .build();

                // 无网络时 ，使用缓存
                if (!NetUtil.isNetworkConnected( context )) {
                    request = request.newBuilder()
                            .cacheControl(CacheControl.FORCE_CACHE)
                            .build();
                }

                Response response = chain.proceed(request);
                if (NetUtil.isNetworkConnected( context )) {
                    // 有网络时 设置缓存超时时间0个小时
                    int maxAge = 0 * 60;
                    response.newBuilder()
                            .addHeader("Cache-Control", "public, max-age=" + maxAge)
                            // 清除头信息，因为服务器如果不支持，会返回一些干扰信息，不清除下面无法生效
                            .removeHeader("Pragma")
                            .build();
                } else {
                    // 无网络时，设置超时为1周
                    int maxStale = 60 * 60 * 24 * 7;
                    response.newBuilder()
                            .addHeader("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                            .removeHeader("Pragma")
                            .build();
                }
                return response;
            }

        };

        OkHttpClient httpClient = new OkHttpClient.Builder()
                .addInterceptor(logging)
                .cache(cache)
                .addInterceptor(interceptor)
                .build();

        return httpClient;
    }
}
